-- 下单锁库传入的数据格式,对于redis来说,lua是原子性的,有事务的

-- 检验库存信息 这里的key是
local cachePrefix = KEYS[1]
local orderNumber = KEYS[2]
local activityId = KEYS[3]
local prodCount = tonumber(KEYS[4])
local userId = KEYS[5]
local maxNum = tonumber(KEYS[6])
local skuId = KEYS[7]
local pointId = KEYS[8]
local currentTime = KEYS[8]
local boughtNum = 0

-- 限购
if maxNum ~= -1 then
    if (redis.call('exists', cachePrefix.."buy:"..activityId.."_"..userId) == 1) then
        -- 用户已购数量
        boughtNum = tonumber(redis.call('get', cachePrefix.."buy:"..activityId.."_"..userId))
    end
    if maxNum < (boughtNum + prodCount) then
        return "-2"
    end
end

-- 因为有可能库存从别的地方扣减，这里只做锁定和订单的记录
local mgetSkuKeys = {}
local msetSkuKV = {}
if prodCount > 0 then
    -- 下面通过get获取当前的库存数量
    table.insert(mgetSkuKeys, cachePrefix.."stock:"..activityId.."_"..skuId)
    table.insert(mgetSkuKeys, cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId)
    local stockStr = redis.call('mget', unpack(mgetSkuKeys));

    local stock = tonumber(stockStr[1])
    local pointStock = tonumber(stockStr[2])



    if pointStock == nil or prodCount > pointStock then
        -- 库存不足返回-1
        return "-1"
    end

    -- 批量更新剩余库存

    -- 总库存
    table.insert(msetSkuKV, cachePrefix.."stock:"..activityId.."_"..skuId)
    table.insert(msetSkuKV, stock - prodCount)
    -- 区域库存
    table.insert(msetSkuKV, cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId)
    table.insert(msetSkuKV, pointStock - prodCount)
end

-- 保存锁定记录
local lockKey = cachePrefix.."lock:"..orderNumber
table.insert(msetSkuKV, lockKey)
table.insert(msetSkuKV, tostring(prodCount))
-- 限购的秒杀商品才需要更新购买数量
if maxNum ~= -1 then
    -- 更新购买数量
    table.insert(msetSkuKV, cachePrefix.."buy:"..activityId.."_"..userId)
    table.insert(msetSkuKV, boughtNum + prodCount)
end
redis.call('mset',unpack(msetSkuKV))


-- 添加锁定明细记录 - 用于订单创建失败时，解锁库存  key-订单编号_活动id_仓库id_skuId   value-操作数量
redis.call('rpush', cachePrefix.."seckill_order_lock_log", orderNumber.."_"..pointId.."_"..skuId.."_"..currentTime.."_"..activityId.."_"..prodCount.."_"..userId)

return "1"
